package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.ItemVo;
import com.atguigu.gulimall.ware.vo.MergePucharseVo;
import com.atguigu.gulimall.ware.vo.PurchaseVo;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;

import com.atguigu.common.gulimallEnum.purchaseEnum;
import com.atguigu.common.gulimallEnum.purchaseNeedEnum;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryUnreceiveForm(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", purchaseEnum.PURCHASR_FORM_CREATED.getCode()).or().eq("status", purchaseEnum.PURCHASR_FORM_DISTRIBUTE.getCode());
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }


    @Override
    public void mergePurchase(MergePucharseVo mergePucharseVo) {
        //采购单编号(如果没有去指定某个采购单编号的话。则默认去新建一个采购单)
        Long purchaseId = mergePucharseVo.getPurchaseId();
        if (purchaseId == null) {
            //新创建一个采购单，将采购项放到新建得采购单中
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(purchaseEnum.PURCHASR_FORM_CREATED.getCode().intValue());
            //设置一个默认的优先级1,可能后面要根据优先级来进行排序
            purchaseEntity.setPriority(1);
            //保存采购单
            this.baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //不为空则去进行修改操作。将两个采购需求的采购单的编号设置为传入的采购单编号
        List<Long> items = mergePucharseVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> entityList = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            return detailEntity;
        }).collect(Collectors.toList());

        //批量修改
        purchaseDetailService.updateBatchById(entityList);
    }

    @Override
    public void receivePurchase(List<Long> ids) {
        //筛选采购单:要领取的采购单的状态必须为新建或者已经分配的状态
        List<PurchaseEntity> collect = ids.stream().map(item -> {
            PurchaseEntity entiity = this.getById(item);
            return entiity;
        }).filter(entity -> {
            if (entity.getStatus() == purchaseEnum.PURCHASR_FORM_CREATED.getCode().intValue() ||
                    entity.getStatus() == purchaseEnum.PURCHASR_FORM_DISTRIBUTE.getCode().intValue()) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());


        //修改采购单的状态
        collect.forEach(item -> {
            //设置采购单的状态为已领取
            item.setStatus(purchaseEnum.PURCHASR_FORM_RECEIVE.getCode().intValue());
            this.updateById(item);
        });

        //修改采购需求的状态为正在采购
        List<Long> purchaseIdList = collect.stream().map(item -> {
            Long id = item.getId();
            //查询到当前采购单所绑定的所有的采购项
//             purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
//            purchaseDetailService.get
            return id;
        }).collect(Collectors.toList());

        QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.in("purchase_id", purchaseIdList);
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.list(wrapper);
        //绑定的所有的采购需求
        System.out.println("purchaseDetailEntityList:" + purchaseDetailEntityList);
        List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntityList.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getId());
            purchaseDetailEntity.setStatus(purchaseNeedEnum.PURCHASE_PURCHASEING.getCode().intValue());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //批量更新
        purchaseDetailService.updateBatchById(detailEntityList);
    }

    //完成采购需求
    @Override
    public void finishPurchase(PurchaseVo purchaseVo) {
        //采购单ID
        Long id = purchaseVo.getId();
        PurchaseEntity purchaseEntity = this.getById(id);
        //1.根据采购项的状态来设置采购单的状态为已完成或者是有异常
        //采购项
        List<ItemVo> items = purchaseVo.getItems();
        boolean flag = true;
        for (ItemVo item : items) {
            //含有失败的情况
            if (item.getStatus() == purchaseNeedEnum.PURCHASE_FAILED.getCode().intValue()) {
                flag = false;
            }
        }
        if (flag) {
            //采购项都成功，设置采购单的状态为已完成
            purchaseEntity.setStatus(purchaseEnum.PURCHASR_FORM_FINISHED.getCode().intValue());
            this.updateById(purchaseEntity);
        } else {
            //设置采购单的状态为异常状态
            purchaseEntity.setStatus(purchaseEnum.PURCHASR_FORM_HASERROR.getCode().intValue());
            this.updateById(purchaseEntity);
        }


        //2.更新采购项的状态
        //2.1 如果采购项是已完成，则更新状态为已完成。并且增加响应的sku商品的库存
        //2.1.1 如果商品之前没有库存，则进行新增操作，如果有则进行修改操作
        //2.2 如果采购项为采购失败，则更新状态为采购失败
        List<PurchaseDetailEntity> entityList = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
            if (detail==null){
                //
                throw new RuntimeException("库中没有该采购项的信息");
//                log.error("库中没有该采购项的信息：");
            }
            detailEntity.setId(item.getItemId());
            Integer status = item.getStatus();
            //采购成功
            if (status==purchaseNeedEnum.PURCHASE_FINISHED.getCode().intValue()){
                //修改库存
//                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                Long skuId = detail.getSkuId();
                Long wareId = detail.getWareId();
                Integer skuNum = detail.getSkuNum();
                wareSkuService.addStock(skuId,wareId,skuNum);
            }
            //更改采购项的状态
            detailEntity.setStatus(status);




            return detailEntity;
        }).collect(Collectors.toList());
        //批量更新采购项的状态
        purchaseDetailService.updateBatchById(entityList);

        //根据采购项的状态去更改库存



    }

    /**
     *   List<PurchaseDetailEntity> purchaseDetailEntities = entityList.stream().map(e -> {
     *                 PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
     *                 detailEntity.setId(e.getId());
     *                 detailEntity.setStatus(purchaseNeedEnum.PURCHASE_PURCHASEING.getCode().intValue());
     *                 return detailEntity;
     *             }).collect(Collectors.toList());
     *             purchaseDetailService.updateBatchById(purchaseDetailEntities);
     */

}